package ui

import (
	"clipPaste/internal/keyboard"
	"clipPaste/internal/storage"
	"sort"
	"strings"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type HistoryWindow struct {
	window   fyne.Window
	app      fyne.App
	store    *storage.Manager
	clips    []*storage.ClipItem
	pageSize int
	content  *fyne.Container
}

func NewHistoryWindow(app fyne.App, store *storage.Manager) *HistoryWindow {
	// 设置应用名称
	app.SetIcon(theme.ContentPasteIcon())
	app.Settings().SetTheme(theme.DarkTheme())

	window := app.NewWindow("Clip Paste") // 设置窗口标题
	hw := &HistoryWindow{
		window:   window,
		app:      app,
		store:    store,
		pageSize: 7,
	}

	hw.createUI()
	return hw
}

func (hw *HistoryWindow) createUI() {
	// 创建横向滚动容器
	hw.content = container.NewHBox()

	// 创建主布局
	mainContainer := container.NewVBox(
		hw.createSearchBar(),             // 搜索栏
		container.NewHScroll(hw.content), // 可横向滚动的内容区
	)

	// 设置窗口属性
	hw.window.SetContent(mainContainer)
	hw.window.Resize(fyne.NewSize(1200, 200)) // 宽而矮的窗口

	// 加载初始数据
	hw.loadClips()
}

func (hw *HistoryWindow) createSearchBar() fyne.CanvasObject {
	searchEntry := widget.NewEntry()
	searchEntry.SetPlaceHolder("搜索剪贴板历史...")
	searchEntry.OnChanged = func(text string) {
		hw.filterClips(text)
	}

	return container.NewHBox(
		widget.NewIcon(theme.SearchIcon()),
		searchEntry,
	)
}

func (hw *HistoryWindow) createClipCard(clip *storage.ClipItem) fyne.CanvasObject {
	// 创建图标
	var icon *widget.Icon
	if clip.Type == storage.TypeImage {
		icon = widget.NewIcon(theme.FileImageIcon())
	} else {
		icon = widget.NewIcon(theme.DocumentIcon())
	}

	// 创建时间标签
	timeLabel := widget.NewLabel(formatTime(clip.Timestamp))
	timeLabel.TextStyle = fyne.TextStyle{Italic: true}

	// 创建内容预览文本
	content := canvas.NewText(formatContent(clip.Content), theme.ForegroundColor())
	content.TextStyle = fyne.TextStyle{
		Monospace: true,
	}
	content.TextSize = 14

	// 创建内容容器，确保文本正确换行
	contentContainer := container.NewHScroll(container.NewPadded(content))

	// 创建卡片容器
	card := container.NewVBox(
		container.NewHBox(
			icon,
			timeLabel,
		),
		contentContainer,
	)

	// 设置卡片样式
	cardContainer := container.NewPadded(
		container.NewBorder(
			nil, nil, nil, nil,
			card,
		),
	)

	// 创建可点击的容器
	clickable := widget.NewButton("", func() {
		hw.window.Clipboard().SetContent(clip.Content)
		hw.window.Hide()
		keyboard.SimulatePaste()
	})

	// 设置按钮样式
	clickable.Importance = widget.LowImportance
	clickable.Hidden = true

	// 创建最终的组合容器
	return container.NewMax(
		cardContainer,
		clickable,
	)
}

func (hw *HistoryWindow) loadClips() {
	// 清空现有内容
	hw.content.RemoveAll()

	// 获取并排序剪贴板项
	allClips, _ := hw.store.GetClips()
	sortClipsByTime(allClips)

	// 限制显示数量
	if len(allClips) > hw.pageSize {
		allClips = allClips[:hw.pageSize]
	}

	// 创建并添加卡片
	for _, clip := range allClips {
		card := hw.createClipCard(clip)
		hw.content.Add(card)
	}

	// 刷新显示
	hw.content.Refresh()
}

func (hw *HistoryWindow) filterClips(searchText string) {
	allClips, _ := hw.store.GetClips()
	sortClipsByTime(allClips)

	// 清空现有内容
	hw.content.RemoveAll()

	// 过滤并添加匹配的项
	count := 0
	for _, clip := range allClips {
		if strings.Contains(strings.ToLower(clip.Content), strings.ToLower(searchText)) {
			card := hw.createClipCard(clip)
			hw.content.Add(card)
			count++
			if count >= hw.pageSize {
				break
			}
		}
	}

	hw.content.Refresh()
}

func (hw *HistoryWindow) Show() {
	if hw.window == nil {
		return
	}

	// 刷新数据
	hw.loadClips()

	// 设置窗口大小
	hw.window.Resize(fyne.NewSize(1200, 200))

	// 显示窗口
	hw.window.Show()
	hw.window.RequestFocus()
}

func formatTime(t time.Time) string {
	now := time.Now()
	if t.Year() == now.Year() && t.Month() == now.Month() && t.Day() == now.Day() {
		return "今天 " + t.Format("15:04:05")
	}
	return t.Format("01-02 15:04")
}

func formatContent(content string) string {
	if content == "" {
		return ""
	}

	// 保持原始空格和换行，但限制长度
	runes := []rune(content)

	// 移除开头和结尾的空白字符
	content = strings.TrimSpace(string(runes))
	runes = []rune(content)

	// 如果内容过长，截取并添加省略号
	if len(runes) > 100 {
		// 确保不会截断UTF-8字符
		return string(runes[:97]) + "..."
	}

	return content
}

func sortClipsByTime(clips []*storage.ClipItem) {
	sort.Slice(clips, func(i, j int) bool {
		return clips[i].Timestamp.After(clips[j].Timestamp)
	})
}
